﻿using System.Text;

namespace ECommon
{
    /// <summary>
    /// 31进制工具
    /// </summary>
    public static partial class Digit31Tool
    {
        /// <summary>
        /// 十进制数转换为31进制数
        /// </summary>
        /// <param name="val">十进制数</param>
        /// <returns>31进制字符串</returns>
        public static string DecToDigit(long val)
        {
            if (val <= 0)
            {
                return KEYWORD[0].ToString();
            }
            List<long> list = new List<long>();
            while (val / KEYWORD.Count != 0)
            {
                list.Add((val % KEYWORD.Count));
                val = val / KEYWORD.Count;
            }
            list.Add(val);
            list.Reverse();
            StringBuilder sb = new StringBuilder();
            list.ForEach(a => { sb.Append(KEYWORD[Convert.ToInt32(a)]); });
            return sb.ToString();
        }

        /// <summary>
        /// 31进制数转换为十进制数
        /// </summary>
        /// <param name="strDigit">31进制字符串</param>
        /// <returns>十进制数</returns>
        public static long DigitToDec(string strDigit)
        {
            if (string.IsNullOrEmpty(strDigit))
            {
                return 0;
            }
            List<long> elements = strDigit.ToList().Select(a => KEYWORD.FindIndex(b => b == a) * 1L).ToList();
            elements.Reverse();
            double res = 0;
            for (int i = elements.Count - 1; i >= 0; i--)
            {
                res += elements[i] * Math.Pow(KEYWORD.Count, i);
            }
            return Convert.ToInt64(res);
        }

        /// <summary>
        /// 关键字
        /// </summary>
        private static List<char> KEYWORD = new List<char>() { 'u', 'b', 'S', 'z', 'g', 'X', 'E', 'l', '2', 'J', 'q', '7', 'O', 'v', 'c', 'T', 'A', 'h', 'Y', 'F', 'm', '3', 'K', 'r', '8', 'P', 'w', 'd', 'U', 'B', 'i', 'Z', 'G', 'n', '4', 'L', 's', '9', 'Q', 'x', 'e', 'V', 'C', 'j', '0', 'H', 'o', '5', 'M', 't', 'a', 'R', 'y', 'f', 'W', 'D', 'k', '1', 'I', 'p', '6', 'N' };
    }
}